package com.scalar.chiptrack.finance.openpo.forms;

import java.util.ArrayList;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.ClientInfo;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.finance.openpo.PurchaseOrderLineItem;
import com.scalar.chiptrack.finance.openpo.PurchaseOrderLineItemList;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.ScalarException;

/**
 * Created by IntelliJ IDEA.
 * User: Phani Raja Kumar
 * Date: Feb 16, 2005
 * Time: 7:41:45 PM
 */
public class PurchaseOrderForm extends ActionForm {

	private int purchaseOrder_Id;
	private String purchaseOrderNumber;
    private int poType;
    private String poTypeLabel;
    private String vendorName;
    private int vendor_id;
    private String purchaseOrderDate;
    private String customerName;
    private int customer_Id;
    private int billingAddress_id 	= -1;
    private int shippingAddress_id  = -1;
    private Address billingAddress 	= null;
    private Address shippingAddress = null;

    private String vendorQuoteNumber;
    private int openPurchaseOrder_Id;
    private String openPurchaseOrderNumber;
    private String remainingOpenPOAmt = null;
    private String comments;
    private String status;

	private String contactPerson	= null;
	private ArrayList shippingContactPersonList = null;
	private ArrayList shippingAddressList = null;

    private double subTotal;
    private double freight;
    private double tradeDiscount;
    private double miscellaneous;
    private double tax;
    private double total;

    private double totalAsInDatabase;
    private String poTaxType = null;
    private String packgeType = null;
    private String validToDate 		= null;
    private double poMaxAmt;
    private double prevReceiptsTotal;

    public double getTotalAsInDatabase() {
        return totalAsInDatabase;
    }

    public void setTotalAsInDatabase(double totalAsInDatabase) {
        this.totalAsInDatabase = totalAsInDatabase;
    }


    private int  revisionNo;
    private ClientInfo clientInfo = null;

    private PurchaseOrderLineItemList purchaseOrderLineItemList;
    private int shippingMethodId;
    private String payTerms;
    private ArrayList shippingMethodsList;
    private ArrayList payTermsList;
    private String newShippingMethod;
    private String newShippingAccount;
    private String newPayTerms;
    private String shipMethod;

    public PurchaseOrderForm()
    {
		purchaseOrder_Id = -1;
        purchaseOrderNumber = null;
		poType = -1;
        poTypeLabel = null;
        vendorName = null;
		vendor_id = -1;
        purchaseOrderDate = null;
		customer_Id = -1;
        customerName = null;

        vendorQuoteNumber = null;
        openPurchaseOrderNumber = null;
		openPurchaseOrder_Id = -1;
        purchaseOrderLineItemList = new PurchaseOrderLineItemList();
		comments = null;
		status = null;

        subTotal = 0.0;
        freight = 0.0;
        tradeDiscount = 0.0;
        miscellaneous = 0.0;
        tax = 0.0;
        total = 0.0;
        poTaxType = "0";
    }
	/**
	 * @return
	 */
	public String getComments()
	{
		return comments;
	}

	/**
	 * @return
	 */
	public int getCustomer_Id()
	{
		return customer_Id;
	}

	/**
	 * @return
	 */
	public String getCustomerName()
	{
		return customerName;
	}

	/**
	 * @return
	 */
	public double getFreight()
	{
		return freight;
	}

     /**
     *
     * @return Freight as string
     */
    public String getFreightAsString()
    {
        DecimalFormat formatter = new DecimalFormat("0.00");
        String output = formatter.format( freight);
        return output;
    }

	/**
	 * @return
	 */
	public double getMiscellaneous()
	{
		return miscellaneous;
	}

    /**
     *
     * @return Miscellaneous as string
     */
    public String getMiscellaneousAsString()
    {
        DecimalFormat formatter = new DecimalFormat("0.00");
        String output = formatter.format( miscellaneous);
        return output;
    }

	/**
	 * @return
	 */
	public int getOpenPurchaseOrder_Id()
	{
		return openPurchaseOrder_Id;
	}

	/**
	 * @return
	 */
	public String getOpenPurchaseOrderNumber()
	{
		return openPurchaseOrderNumber;
	}

	/**
	 * @return
	 */
	public int getPurchaseOrder_Id()
	{
		return purchaseOrder_Id;
	}

	/**
	 * @return
	 */
	public String getPurchaseOrderDate()
	{
		return purchaseOrderDate;
	}

	/**
	 * @return
	 */
	public PurchaseOrderLineItemList getPurchaseOrderLineItemList()
	{
		return purchaseOrderLineItemList;
	}

	/**
	 * @return
	 */
	public String getPurchaseOrderNumber()
	{
		return purchaseOrderNumber;
	}

	/**
	 * @return
	 */
	public int getPoType()
	{
		return poType;
	}

    public String getPoTypeLabel() {
        return poTypeLabel;
    }

    public int getBillingAddress_id()
    {
        return billingAddress_id;
    }

    /**
     * @return
     */
    public int getShippingAddress_id()
    {
        return shippingAddress_id;
    }

    /**
     * @param i
     */
    public void setBillingAddress_id(int i)
    {
        billingAddress_id = i;
    }

    /**
     * @return
     */
    public Address getShippingAddress()
    {
        return shippingAddress;
    }

    /**
     * @param address
     */
    public void setShippingAddress(Address address)
    {
        shippingAddress = address;
    }

    /**
     * @return
     */
    public Address getBillingAddress()
    {
        return billingAddress;
    }

    /**
     * @param address
     */
    public void setBillingAddress(Address address)
    {
        billingAddress = address;
    }

    /**
     * @param i
     */
    public void setShippingAddress_id(int i)
    {
        shippingAddress_id = i;
    }

    public String getShippingAddressAsString()
    {
        return formateAddress( shippingAddress );
    }

    public String getBillingAddressAsString()
    {
        return formateAddress( billingAddress );
    }

	/**
	 * @return
	 */
	public double getSubTotal()
	{
		return subTotal;
	}

    public String getSubTotalAsString()
    {
        DecimalFormat formatter = new DecimalFormat("0.00");
        String output = formatter.format( subTotal);
        return output;
    }

	/**
	 * @return
	 */
	public double getTax()
	{
		return tax;
	}

    /**
     *
     * @return tax as string
     */
    public String getTaxAsString()
    {
        DecimalFormat formatter = new DecimalFormat("0.00");
        String output = formatter.format( tax);
        return output;
    }


	/**
	 * @return
	 */
	public double getTotal()
	{
		return total;
	}

    public String getTotalAsString()
    {
        DecimalFormat formatter = new DecimalFormat("0.00");
        String output = formatter.format( total);
        return output;
    }
	/**
	 * @return
	 */
	public double getTradeDiscount()
	{
		return tradeDiscount;
	}

    /**
     *
     * @return TradeDiscount as string
     */
    public String getTradeDiscountAsString()
    {
        DecimalFormat formatter = new DecimalFormat("0.00");
        String output = formatter.format( tradeDiscount);
        return output;
    }

	/**
	 * @return
	 */
	public int getVendor_id()
	{
		return vendor_id;
	}

	/**
	 * @return
	 */
	public String getVendorName()
	{
		return vendorName;
	}

	/**
	 * @return
	 */
	public String getVendorQuoteNumber()
	{
		return vendorQuoteNumber;
	}

	/**
	 * @param string
	 */
	public void setComments(String string)
	{
		comments = string;
	}

	/**
	 * @param i
	 */
	public void setCustomer_Id(int i)
	{
		customer_Id = i;
	}

	/**
	 * @param string
	 */
	public void setCustomerName(String string)
	{
		customerName = string;
	}

	/**
	 * @param l
	 */
	public void setFreight(double l)
	{
		freight = l;
	}

	/**
	 * @param l
	 */
	public void setMiscellaneous(double l)
	{
		miscellaneous = l;
	}

	/**
	 * @param i
	 */
	public void setOpenPurchaseOrder_Id(int i)
	{
		openPurchaseOrder_Id = i;
	}

	/**
	 * @param string
	 */
	public void setOpenPurchaseOrderNumber(String string)
	{
		openPurchaseOrderNumber = string;
	}

	/**
	 * @param i
	 */
	public void setPurchaseOrder_Id(int i)
	{
		purchaseOrder_Id = i;
	}

	/**
	 * @param string
	 */
	public void setPurchaseOrderDate(String string)
	{
		purchaseOrderDate = string;
	}

	/**
	 * @param list
	 */
	public void setPurchaseOrderLineItemList(PurchaseOrderLineItemList list)
	{
		purchaseOrderLineItemList = list;
	}

	/**
	 * @param string
	 */
	public void setPurchaseOrderNumber(String string)
	{
		purchaseOrderNumber = string;
	}

	/**
	 * @param i
	 */
	public void setPoType(int i)
	{
		poType = i;
	}


    public void setPoTypeLabel(String poTypeLabel) {
        this.poTypeLabel = poTypeLabel;
    }

	/**
	 * @param l
	 */
	public void setSubTotal(double l)
	{
		subTotal = l;
	}

	/**
	 * @param l
	 */
	public void setTax(double l)
	{
		tax = l;
	}

	/**
	 * @param l
	 */
	public void setTotal(double l)
	{
		total = l;
	}

	/**
	 * @param l
	 */
	public void setTradeDiscount(double l)
	{
		tradeDiscount = l;
	}

	/**
	 * @param i
	 */
	public void setVendor_id(int i)
	{
		vendor_id = i;
	}

	/**
	 * @param string
	 */
	public void setVendorName(String string)
	{
		vendorName = string;
	}

	/**
	 * @param string
	 */
	public void setVendorQuoteNumber(String string)
	{
		vendorQuoteNumber = string;
	}

	/**
	 * @return
	 */
	public String getStatus()
	{
		return status;
	}

	/**
	 * @param string
	 */
	public void setStatus(String string)
	{
		status = string;
	}

    public int getRevisionNo() {
        return revisionNo;
    }

    public void setRevisionNo(int revisionNo) {
        this.revisionNo = revisionNo;
    }

    public ClientInfo getClientInfo() {
        return clientInfo;
    }

    public void setClientInfo(ClientInfo clientInfo) {
        this.clientInfo = clientInfo;
    }
    public String getPoTaxType() {
        return poTaxType;
    }

    public void setPoTaxType(String poTaxType) {
        this.poTaxType = poTaxType;
    }

    public String formateAddress( Address address )
    {
        StringBuffer formatedAddress = new StringBuffer();
        formatedAddress.append( formatAddressAsStringForHTML( address ) );
        return formatedAddress.toString();
    }

    public String getPackgeType() {
        return packgeType;
    }

    public void setPackgeType(String packgeType) {
        this.packgeType = packgeType;
    }

    public String getClientAddrWithOutEmailObjFormatted()
	{
        Address add = clientInfo.getAddress();
        StringBuffer formatAddress = new StringBuffer();

        formatAddress.append ( ( ( clientInfo.getClientName() == null ) || ( ( clientInfo.getClientName().trim().length() == 0 ) ) ) ? "" :"<BR>" +  clientInfo.getClientName() );

        formatAddress.append ( ( ( add.getAddress1() == null ) || ( ( add.getAddress1().trim().length() == 0 ) ) ) ? "" :"<BR>" +  add.getAddress1() );
        formatAddress.append ( ( ( add.getAddress2() == null ) || ( ( add.getAddress2().trim().length() == 0 ) ) ) ? "" :"<BR>" + add.getAddress2() );
        formatAddress.append ( ( ( add.getAddress3() == null ) || ( ( add.getAddress3().trim().length() == 0 ) ) ) ? "" : "<BR>" + add.getAddress3() );
        formatAddress.append ( ( ( add.getAddress4() == null ) || ( ( add.getAddress4().trim().length() == 0 ) ) ) ? "" : "<BR>" + add.getAddress4() );

        String formatState = PurchaseOrderForm.getFormatedCityState(add);
        if ( formatState.trim().length() !=0 )
           formatAddress.append ("<BR>"+formatState);
        formatAddress.append ( ( ( add.getPhoneNumber() != null ) && ( add.getPhoneNumber().trim().length() > 0 ) ) ?  "<BR>Tel: "+ add.getPhoneNumber() : "" );
        formatAddress.append ( ( ( add.getFaxNumber() != null ) && ( add.getFaxNumber().trim().length() > 0 ) ) ?  "<BR>Fax: "+ add.getFaxNumber() : "" );

        return formatAddress.toString() ;
	}
     public static String getFormatedCityState( Address add )
	{
	    String addr = "";
        if( add.getCity() != null && add.getCity() .trim() .length() != 0 )
            addr = add.getCity() + ",&nbsp;" ;
        if (  add.getState() != null  &&  add.getState().trim().length() != 0 )
		    addr =  addr  + add.getState();
		if( add.getZipCode() != null &&  add.getZipCode().trim().length() != 0 )
		{
		     if ( addr.trim().length() !=0 )
		         addr = addr + "&nbsp;-&nbsp;" + add.getZipCode();
		    else
				 addr = addr + add.getZipCode();
		}
		if( add.getCountry() != null && add.getCountry().trim().length() != 0 )
	    {
	        if ( addr.trim().length() != 0 )
			    addr = addr + ",&nbsp;" + add.getCountry();
			else
			    addr = addr + add.getCountry();
	   	}

		return addr;
	}

    /**
     *
     * @param address Address object to format
     * @return formatted address as String or null
     */
    public String formatAddressAsStringForHTML( Address address )
    {
        if ( address != null )
        {
            StringBuffer tempAddress = new StringBuffer( "" );
            String contactPerson = address.getContactPerson();
            String address1 = address.getAddress1();
            String address2 = address.getAddress2();
            String address3 = address.getAddress3();
            String address4 = address.getAddress4();
            String city = address.getCity();
            String zipCode = address.getZipCode();
            String state = address.getState();
            String country = address.getCountry();
            String phoneNumber = address.getPhoneNumber();
            String cellNumber = address.getCellNumber();
            String faxNumber = address.getFaxNumber();
            String email = address.getEmail();

            if( contactPerson != null && !( contactPerson.trim().equals( "" ) ) )
            {
                tempAddress.append( contactPerson + "\n" );
            }
            if( address1 != null && !( address1.trim().equals( "" ) ) )
            {
                tempAddress.append( address1 + "\n" );
            }
            if( address2 != null && !( address2.equals( "" ) ) )
            {
                tempAddress.append( address2 + "\n" );
            }
            if( address3 != null && !( address3.equals( "" ) ) )
            {
                tempAddress.append( address3 + "\n" );
            }
            if( address4 != null && !( address4.equals( "" ) ) )
            {
                tempAddress.append( address4 + "\n" );
            }
            if( city != null && !( city.equals( "" ) ) )
            {
                tempAddress.append( city + "\n" );
            }
            if( state != null && !( state.equals( "" ) ) )
            {
                tempAddress.append( state );
            }


            if( zipCode != null && !( zipCode.equals( "" ) ) )
            {
                if( state != null && !( state.equals( "" ) ) )
                {
                    tempAddress.append( " - " );
                }
                tempAddress.append( zipCode );
            }

            if( country != null && !( country.equals( "" ) ) )
            {
                if( ( zipCode != null && !( zipCode.equals( "" ) ) ) || ( state != null && !( state.equals( "" ) ) ) )
                {
                    tempAddress.append( ", " );
                }
                tempAddress.append( country );
            }
            tempAddress.append( ( phoneNumber != null && !( phoneNumber.equals( "" ) ) ) ? "\n\nTel:" + phoneNumber : "" );
            tempAddress.append( ( cellNumber != null && !( cellNumber.equals( "" ) ) ) ? "\nCell:" + cellNumber : "" );
            tempAddress.append( ( faxNumber != null && !( faxNumber.equals( "" ) ) ) ? "\nFax:" + faxNumber : "" );
            tempAddress.append( ( email != null && !( email.equals( "" ) ) ) ? "\nEmail:" + email : "" );
            return tempAddress.toString();
        }
        return null;
    }

    /**
     *
     * @param address Address object to format
     * @param addressType This parameter represents the node name in the XML file, in which the actual address is encapsulated
     * @return formatted address as String or null
     */
    public String formatAddressAsStringForXML( Address address, String addressType )
    {
        if( address != null )
        {
            StringBuffer buf = new StringBuffer();
            String address1 = "";
            String address2 = "";
            String address3 = "";
            String address4 = "";

            if ( !(address.getAddress1()==null || address.getAddress1().trim().length() == 0) )
            {
                address1 =  address.getAddress1();
            }
            if ( !(address.getAddress2()==null || address.getAddress2().trim().length() == 0) )
            {
                address2 =  address.getAddress2();
            }
            if ( !(address.getAddress3()==null || address.getAddress3().trim().length() == 0) )
            {
                address3 =  address.getAddress3();
            }
            if ( !(address.getAddress4()==null || address.getAddress4().trim().length() == 0) )
            {
                address4 =  address.getAddress4();
            }
            buf.append ( "<"+addressType+">" + "\n" );
            if( address.getContactPerson() != null && address.getContactPerson().trim().length() !=0 )
            {
            buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
            }
            buf.append ( "<address1><![CDATA[" + address1 + "]]></address1>" + "\n" );
            buf.append ( "<address2><![CDATA[" + address2 + "]]></address2>" + "\n" );
            buf.append ( "<address3><![CDATA[" + address3 + "]]></address3>" + "\n" );
            buf.append ( "<address4><![CDATA[" + address4 + "]]></address4>" + "\n" );
            buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
            buf.append ( "<stateZipCountry><![CDATA[" );
            if(address.getState ()!=null && !(address.getState ().equals("")))
            {
                buf.append(address.getState ());
            }
            if(address.getZipCode()!=null && !(address.getZipCode().equals("")))
            {
                if(address.getState ()!=null && !(address.getState ().equals("")))
                {
                    buf.append(" - ");
                }
                buf.append(address.getZipCode());
            }
            if(address.getCountry ()!=null && !(address.getCountry ().equals("")))
            {
                if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
                {
                    buf.append(", ");
                }
                buf.append(address.getCountry ());
            }
            buf.append ( "]]></stateZipCountry>" + "\n" );
            buf.append ( "<phone><![CDATA[" + ( address.getPhoneNumber () != null && !address.getPhoneNumber().equals("") ?  "Tel:"+ address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
            buf.append ( "<cell><![CDATA[" + ( address.getCellNumber () != null && !address.getCellNumber().equals("") ?  "Cell:"+address.getCellNumber () : "" ) + "]]></cell>" + "\n" );
            buf.append ( "<fax><![CDATA[" + ( address.getFaxNumber () != null && !address.getFaxNumber().equals("") ?  "Fax:" + address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
            //buf.append ( "<email><![CDATA[" + ( address.getEmail () != null && !address.getEmail().equals("") ?  "EMail:" + address.getEmail () : "" ) + "]]></email>" + "\n" );
            buf.append ( "</"+addressType+">" + "\n" );
            return buf.toString() ;
        }
        return null;
    }



    /**
     * For resetting the PurchaseOrderForm Values
     * @param mapping
     * @param request
     */
    public void reset( ActionMapping mapping, HttpServletRequest request )
    {
        PurchaseOrderLineItem purchaseOrderLineItem = null;
        PurchaseOrderLineItemList  purchaseOrderLineItemListTemp = new PurchaseOrderLineItemList();
        for( int i=0; i < purchaseOrderLineItemList.size(); i++ )
        {
            purchaseOrderLineItem = ( PurchaseOrderLineItem )purchaseOrderLineItemList.get( i );
            purchaseOrderLineItem.setCancel( false );
            purchaseOrderLineItemListTemp.add(purchaseOrderLineItem);
        }
        this.setPurchaseOrderLineItemList( purchaseOrderLineItemListTemp );
    }



	/**
	 * @return
	 */
	public String getContactPerson()
	{
		return contactPerson;
	}

	/**
	 * @return
	 */
	public ArrayList getShippingAddressList()
	{
		return shippingAddressList;
	}

	/**
	 * @return
	 */
	public ArrayList getShippingContactPersonList()
	{
		return shippingContactPersonList;
	}

	/**
	 * @param string
	 */
	public void setContactPerson(String string)
	{
		contactPerson = string;
	}

	/**
	 * @param list
	 */
	public void setShippingAddressList(ArrayList list)
	{
		shippingAddressList = list;
	}

	/**
	 * @param list
	 */
	public void setShippingContactPersonList(ArrayList list)
	{
		shippingContactPersonList = list;
	}

	public ArrayList getFormattedShippingAddressList()
	{
		ArrayList formattedArrayList = new ArrayList();

		if( shippingAddressList != null && shippingAddressList.isEmpty() == false )
		{
			for( int i = 0; i < shippingAddressList.size(); i++ )
			{
				formattedArrayList.add( formatAddressAsStringForHTML( ((Address)shippingAddressList.get( i ) ) ) );
			}
		}

		return formattedArrayList;
	}

	/**
	 * @return
	 */
	public String getRemainingOpenPOAmt()
	{
		return remainingOpenPOAmt;
	}

	/**
	 * @param string
	 */
	public void setRemainingOpenPOAmt(String string)
	{
		remainingOpenPOAmt = string;
	}

    public String getBillingAddressAsStringForHTMLWithBreaks()
    {
        String returnStr = "";
        if( this.getBillingAddress() != null)
        {
            returnStr = this.getBillingAddressAsString().trim().replaceAll("\n","<BR>");
        }
        return returnStr;
    }
    public String getShippingAddressAsStringForHTMLWithBreaks()
    {
        String returnStr = "";
        if( this.getShippingAddress() != null)
        {
            returnStr = this.getShippingAddressAsString().trim().replaceAll("\n","<BR>");
        }
        return returnStr;
    }

    public String  getPurchaseOrderAckHtmlFile( String host, PurchaseOrderForm purchaseOrderForm )
    {
        String filePath = null;
        String psAsHtml = null;

        try{
            psAsHtml = getOpenPOHtmlView ( host, purchaseOrderForm );
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        if ( psAsHtml == null )
        {
            return filePath;
        }

        FileWriter fWriter = null;
        File psAttachment = null;

        try
        {
            String mailingTempDir = ConfigManager.getMailerTempDir ();
            File tempDir = new File ( mailingTempDir ).getCanonicalFile ();
            tempDir.mkdir ();
            String poAttachmentFileName = null;

            poAttachmentFileName = "PurchaseOrder_Ack_" + purchaseOrderForm.getPurchaseOrderNumber() + ".html";
            psAttachment = new File ( tempDir.getCanonicalPath (), poAttachmentFileName );

            psAttachment.deleteOnExit ();

            if ( ( psAttachment.exists () == true ) || ( psAttachment.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( psAttachment, false );

                fWriter.write ( psAsHtml );

                fWriter.close ();
                fWriter = null;

                filePath = psAttachment.getAbsolutePath ();
            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Purchase Order Ack html file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return filePath;
    }

    public String getOpenPOHtmlView( String host, PurchaseOrderForm purchaseOrderForm ) throws ScalarException
    {
        StringBuffer buf = new StringBuffer();

        ArrayList poLineItems    = purchaseOrderForm.getPurchaseOrderLineItemList();
        String scalarLogo 	     = ConfigManager.getScalarLogo();

        buf.append ("<HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE><META http-equiv=Content-Type content='text/html; charset=windows-1252'>\n");

        buf.append ("<style type=\"text/css\">\n");
        buf.append ("#toc a{ font-family: Verdana;font-style : normal ;font-size : 9pt; font-weight :bold;}");
        buf.append ("#toc p{font-family: Verdana;font-style : normal ;font-size : 9pt; font-weight :bold;text-align :center;color :#FFFFFF}");
        buf.append ("#toc {border-style : solid;border-color :#000000 ;border-width :medium }");
        buf.append (".NArialW{ COLOR: #000000;font-family: arial;font-size: 18pt}");
        buf.append (".NArialL{ COLOR: #000000;font-family: verdana;font-size: 8pt;font-weight:bold}");
        buf.append (".NArialR{ COLOR: #000000; FONT-FAMILY: verdana; FONT-SIZE: 7pt; font-weight:bold}");
        buf.append (".NArialRS{ COLOR: #000000; FONT-FAMILY: verdana; FONT-SIZE: 7pt;}");
        buf.append ("</style></head>\n");

        buf.append ("<BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'><br>\n");
        buf.append ("<table width='95%' cellspacing='0' cellpadding='0' border=0 align=right>\n");
        buf.append ("<tr><td width='98%'>\n");

            buf.append ("<table border='0' width='98%'>\n");
            buf.append( "<tr>" );
                buf.append( "<td colspan='5'>" );
                    buf.append( "<table width ='100%'>" );
                        buf.append( "<tr>" );
                            buf.append( "<td width='10%' align='center'><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='5'></td>" );
                            buf.append( "<td width='20%' align='left' valign='top'><img src='http://" + host + "/"+ ConfigManager.getChipTracContext () +"/jsp/includes/images"+scalarLogo+" ' height='84' width='200' border=0></td> " );
                            buf.append( "<td width='40%'  align='center' class='NArialL'><font class='NArialW'>Purchase Order Acknowledgement</font>" );
                            buf.append( purchaseOrderForm.getClientAddrWithOutEmailObjFormatted() ).append("</td>");
                            buf.append( "<td width='20%' align='center'><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='5'></td>" );
                            buf.append( "<td width='10%' align='center'><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='5'></td>" );
                        buf.append( "<tr>" );
                    buf.append( "</table>" );
                buf.append( "</td>" );
            buf.append( "<tr>" );

            buf.append ("<tr height='20'><td colspan='5'></td></tr>\n");
            buf.append ("<tr>\n");
            buf.append ("<td width='38%'>\n");
                buf.append ("<table border=1 width='100%' height='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>\n");
                buf.append ("<tr height='20%'><td class='NArialL' bgcolor='#DEE1E2'>Bill To Address :</td></tr>\n");
                buf.append ("<tr height=20>\n");
                buf.append ("<td class='NArialL' bgcolor='#FFFFEE' valign='top'>\n");
                    buf.append ("<table width='100%' class='NArialL' cellspacing='0' cellpadding='0'>\n");
                    buf.append ("<tr valign='top'><td>\n").append( purchaseOrderForm.getBillingAddressAsStringForHTMLWithBreaks() ).append("</td></tr>\n");
                    buf.append ("</table>\n");
                buf.append ("</td>\n");
                buf.append ("</tr>\n");
                buf.append ("</table>\n");
            buf.append ("</td>\n");
            buf.append ("<td width='22%'></td>\n");
            buf.append ("<td height='38%'>\n");
                buf.append ("<table border=1 width='100%' height='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>\n");
                buf.append ("<tr height='20%'><td class='NArialL' bgcolor='#DEE1E2'>Ship To Address :</td></tr>\n");
                buf.append ("<tr height=20>\n");
                buf.append ("<td class='NArialL' bgcolor='#FFFFEE' valign='top'>\n");
                    buf.append ("<table width='100%' class='NArialL' cellspacing='0' cellpadding='0'>\n");
                    buf.append ("<tr><td>\n").append( purchaseOrderForm.getShippingAddressAsStringForHTMLWithBreaks() ).append("</td></tr>\n");
                buf.append ("</table>\n");
                buf.append ("</td>\n");
                buf.append ("</tr>\n");
                buf.append ("</table>\n");
            buf.append ("</td>\n");
            buf.append ("<td width='2%'></td>\n");
            buf.append ("</tr>\n");
            buf.append ("<tr><td colspan=5><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='5'></td></tr>\n");
            buf.append ("</table>\n");

        buf.append ("</td></tr>\n");

        buf.append ("<tr><td width='98%'> ");
        buf.append ("<table width='98%' cellspacing='0' cellpadding='0' border=0 >\n");
        buf.append ("<tr><td colspan=5><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'' height=5></td></tr>\n");
        buf.append ("<tr><td colspan=5><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'' height=5></td></tr>\n");
        buf.append ("<tr><td colspan=5><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'' height=5></td></tr>\n");
        buf.append ("<tr>\n");
        buf.append ("<td colspan='5'>\n");
            buf.append ("<table width='98%' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0' align='left'>\n");
                buf.append ("<tr height=20>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>PO&nbsp;Number</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>PO&nbsp;Type</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>PO&nbsp;Date</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Vendor&nbsp;Name</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Valid&nbsp;To</td>\n");
                buf.append ("</tr>\n");

                buf.append ("<tr height=20>\n");
                buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center>\n").append( purchaseOrderForm.getPurchaseOrderNumber() ).append("</td>\n");
                buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center nowrap>\n").append( purchaseOrderForm.getPoTypeLabel() ).append("&nbsp;</td>\n");
                buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center nowrap>\n").append( purchaseOrderForm.getPurchaseOrderDate() ).append("&nbsp;</td>\n");
                buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center wrap>\n").append( ( ( purchaseOrderForm.getVendorName() == null ) ? "" : purchaseOrderForm.getVendorName() ) ).append("&nbsp;</td>\n");
                buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center wrap>\n").append( ( ( purchaseOrderForm.getValidToDate() == null ) ? "" : purchaseOrderForm.getValidToDate() ) ).append("&nbsp;</td>\n");
                buf.append ("</tr>\n");

                buf.append ("<tr height=20>\n");
                buf.append ("<td colspan='3' class='NArialL' bgcolor='#DEE1E2' align=center>Shipping Method</td>\n");
                buf.append ("<td colspan='2' class='NArialL' bgcolor='#DEE1E2' align=center>Pay Terms</td>\n");
                buf.append ("</tr>\n");

                buf.append ("<tr height=20>\n");
                buf.append ("<td colspan='3' bgcolor='#FFFFEE' class='NArialL' align=center>\n").append( purchaseOrderForm.getShipMethod() ).append("</td>\n");
                buf.append ("<td colspan='2' bgcolor='#FFFFEE' class='NArialL' align=center nowrap>\n").append( purchaseOrderForm.getPayTerms() ).append("&nbsp;</td>\n");
                buf.append ("</tr>\n");
            buf.append ("</table>\n");
        buf.append ("</td>\n");
        buf.append ("</tr>\n");

        buf.append ("<tr><td width='98%'> ");
            buf.append ("<table width='98%' cellspacing='0' cellpadding='0' border=0 >\n");
            buf.append ("<tr><td><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'' height=5></td></tr>\n");
            buf.append ("<tr><td><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'' height=5></td></tr>\n");
            buf.append ("<tr><td><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'' height=5></td></tr>\n");
            buf.append ("<tr  bgcolor='#DEE1E2'>\n");
            buf.append ("<td><FONT SIZE='3' ><B><U>Comments</U>:</B></FONT><br>&nbsp;&nbsp;&nbsp;&nbsp;<font class='NArialL'>&nbsp;&nbsp;").append( ( (purchaseOrderForm.getComments() != null) ? purchaseOrderForm.getComments() : "</font>") );
            buf.append ("</td>\n");
            buf.append ("</tr>\n");
            buf.append ("</table>\n");
        buf.append("</td></tr>\n");

        buf.append ("<tr><td width='98%'> ");
            buf.append ("<table width='98%' cellspacing='0' cellpadding='0' border=0 >\n");
            buf.append ("<tr><td colspan=5><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'' height=5></td></tr>\n");
            buf.append ("<tr><td colspan=5><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'' height=5></td></tr>\n");
            buf.append ("<tr><td colspan=5><img src='http://" + host  + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'' height=5></td></tr>\n");
            buf.append ("<tr>\n");
            buf.append ("<td colspan='5'>\n");
                buf.append ("<table width='100%' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0' align='center'>\n");
                buf.append ("<tr height=20>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Line&nbsp;Item</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Process&nbsp;Name</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Part&nbsp;Number</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Vendor&nbsp;Part&nbsp;Number</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Description</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>package&nbsp;Type</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Req.&nbsp;Date</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Req.&nbsp;Qty</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Unit&nbsp;Cost($)</td>\n");
                buf.append ("<td class='NArialL' bgcolor='#DEE1E2' align=center>Ext.&nbsp;Cost($)</td>\n");
                buf.append ("</tr>\n");
            int index = 1;
            if ( poLineItems != null )
            {
                for ( int i = 0; i < poLineItems.size(); i++)
                {
                    PurchaseOrderLineItem poLineItem = ( PurchaseOrderLineItem ) poLineItems.get( i );
                    if( !Constants.PURCHASE_ORDER_STATUS_CANCELLED.equalsIgnoreCase( poLineItem.getStatus() ) )
                    {
                        buf.append ("<tr height=20>\n");
                        buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center>\n").append( index++ ).append("</td>\n");
                        buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center nowrap>\n").append( poLineItem.getProcessName() ).append("&nbsp;</td>\n");
                        buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center nowrap>\n").append( poLineItem.getPartNumber() ).append("&nbsp;</td>\n");
                        buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center nowrap>\n").append( poLineItem.getCustomerPartNumber() ).append("&nbsp;</td>\n");
                        buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center wrap>\n").append( poLineItem.getDescription() != null ? poLineItem.getDescription() : "").append("&nbsp;</td>\n");
                        buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center>\n").append( poLineItem.getPackageType() != null ? poLineItem.getPackageType() : "" ).append("&nbsp;</td>\n");
                        buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=center>\n").append( poLineItem.getRequestedDate() != null ? poLineItem.getRequestedDate() : "" ).append("&nbsp;</td>\n");
                        buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=right>&nbsp;\n").append( poLineItem.getRequestedQuantity() ).append("</td>\n");
                        buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=right>&nbsp;\n").append( poLineItem.getUnitCostAsString()).append("</td>\n");
                        buf.append ("<td bgcolor='#FFFFEE' class='NArialL' align=right>&nbsp;\n").append( poLineItem.getExtendedCostAsString() ).append("</td>\n");
                        buf.append ("</tr>\n");
                    }
                }
            }
            buf.append ("</table>\n");
            buf.append ("</td>\n");
            buf.append ("</tr>\n");
            if ( poLineItems != null )
            {
                if( ( index == 1 )&&( poLineItems.size() > 0 ) )
                {
                    buf.append ("<tr height=20>\n");
                        buf.append ("<td bgcolor='#FFFFFF' class='NArialL' align=center wrap>\n").append("<font color='red'  align='center'>All Line Items are cancelled </font>").append("&nbsp;</td>\n");
                    buf.append ("</tr>\n");
                }
                if( ( index != 1 )&&( poLineItems.size() > 0 ) )
                {
                    buf.append ("<tr>\n");
                    buf.append ("<td colspan='5'>\n");
                        buf.append ("<table width='25%' border=1 align=right bordercolor='#000000'  cellspacing='0' cellpadding='0'>\n");
                        buf.append ("<tr><td bgcolor='#DEE1E2' class='NArialL' align=right >Sub Total:$</td><td bgcolor='#FFFFEE' class='NArialL'  align='right'>\n").append( purchaseOrderForm.getSubTotalAsString() ).append("</td></tr>\n");
                        buf.append ("<tr><td bgcolor='#DEE1E2' class='NArialL'  width='65.50%' align=right >Freight:$</td><td bgcolor='#FFFFEE'  class='NArialL' align='right'  width='34.50%'>\n").append( purchaseOrderForm.getFreightAsString() ).append("</td></tr>\n");
                        buf.append ("<tr><td bgcolor='#DEE1E2' class='NArialL' nowrap align=right >Trade Discount:$</td><td bgcolor='#FFFFEE'  class='NArialL' align='right'>\n").append( purchaseOrderForm.getTradeDiscountAsString() ).append("</td></tr>\n");
                        buf.append ("<tr><td bgcolor='#DEE1E2' class='NArialL' align=right >Miscellaneous:$</td><td class='NArialL' bgcolor='#FFFFEE' align='right'>\n").append( purchaseOrderForm.getMiscellaneousAsString() ).append("</td></tr>\n");
                        buf.append ("<tr><td bgcolor='#DEE1E2' class='NArialL' align=right >Tax:$</td><td  class='NArialL' bgcolor='#FFFFEE' align='right'>\n").append( purchaseOrderForm.getTaxAsString() ).append("</td></tr>\n");
                        buf.append ("<tr><td bgcolor='#DEE1E2' class='NArialL' align=right >Order Total:$</td><td  class='NArialL' bgcolor='#FFFFEE' align='right'>\n").append( purchaseOrderForm.getTotalAsString() ).append("</td></tr>\n");
                        buf.append ("</table>\n");
                    buf.append ("</td>\n");
                    buf.append ("</tr>\n");
                }
            }
            buf.append ("</table><br><br><br><br>\n");

        buf.append ("</td></tr>\n");
        buf.append ("</table>\n");

        buf.append ("<table width='60%' border='0'>\n");
        buf.append ("</table>\n");

        buf.append ("</form></html></BODY></HTML>\n");

        return buf.toString();
    }

    public static String getPurchaseOrderAsPDFFile(PurchaseOrderForm purchaseOrderForm )
    {

        String fileXMLPath 		= null;
        String filePDFPath 		= null;
        String fileXSLTPath 	= null;
        FileWriter fWriter 		= null;
        File psPDFAttachment 	= null;
        File psXML 				= null;
        String psAsXML 			= formatAsXML( purchaseOrderForm );
        if( psAsXML == null )
        {
            return fileXMLPath;
        }

        try
        {
            String mailingTempDir 		    = ConfigManager.getMailerTempDir();
            File tempDir 				    = new File ( mailingTempDir ).getCanonicalFile();
            String poAttachmentFileName     = purchaseOrderForm.getPurchaseOrderNumber();
            String xmlFileName 			    = "Purchase_Order_" + poAttachmentFileName + ".xml";
            String  xsltFileName		    = ConfigManager.getPurchaseOrderXml2PdfXslFile();
            String poAttachmentPDFFileName  = "Purchase_Order_" + poAttachmentFileName + ".pdf";

            tempDir.mkdir();

            if( ( poAttachmentFileName != null ) && ( poAttachmentFileName.startsWith( "PO-" ) ) )
            {
                poAttachmentFileName = poAttachmentFileName.substring( 3 );
            }

            psXML = new File( tempDir.getCanonicalPath(), xmlFileName );
            psXML.deleteOnExit();

            psPDFAttachment = new File( tempDir.getCanonicalPath(), poAttachmentPDFFileName );
            psPDFAttachment.deleteOnExit();

            if( ( psXML.exists() == true ) || ( psXML.createNewFile() == true ) )
            {
                fWriter = new FileWriter ( psXML, false);
                fWriter.write ( psAsXML );
                fWriter.close();
                fWriter = null;

                fileXMLPath = psXML .getCanonicalPath() .toLowerCase();
                filePDFPath = psPDFAttachment .getCanonicalPath() .toLowerCase();
                boolean success = PDFGenerator.convertXML2PDF( fileXMLPath, xsltFileName, filePDFPath );
            }
        }
        catch( Exception e )
        {
            System.out.println( "Exception while creating purchase order PDF file");
            e.printStackTrace();
        }
        finally
        {
            if( fWriter != null )
            {
                try
                {
                    fWriter.close();
                    fWriter = null;
                }
                catch( IOException ignore ){}
            }
        }

        return filePDFPath;
    }

    public static String formatAsXML ( PurchaseOrderForm purchaseOrderForm )
    {

        StringBuffer buf 			= new StringBuffer ( 2098 );

        ArrayList poLineItems = purchaseOrderForm.getPurchaseOrderLineItemList();

        String imagesDirLocation 	= ConfigManager.getChipTracImagesDir();
        String scalarLogo 			= ConfigManager.getScalarLogo();

        buf.append ( "<?xml version='1.0' encoding='UTF-8'?>" + "\n" );
        buf.append ( "<purchaseOrder> \n" );

        buf.append ( "<images>\n" );
        buf.append ( "<logo>"+imagesDirLocation + scalarLogo +"</logo> \n" );
        buf.append ( "</images>\n" );

        buf.append ( "<selfAddress> \n" );

        Address address  = new Address();
        try
        {
            address  = purchaseOrderForm.getBillingAddress();
        }
        catch( Exception e)
        {
            e.printStackTrace();
        }
        buf.append ( "<name><![CDATA[" ) .append( ( ( address.getContactPerson() == null ) ? "" : address.getContactPerson() ) ) .append( "]]></name> \n" );
        buf.append ( "<address1><![CDATA[" );
        buf.append ( ( ( address.getAddress1() == null ) ? "" : address.getAddress1().trim() ) );
        buf.append ( "]]></address1> \n" );

        buf.append ( "<address2><![CDATA[" );
        buf.append ( ( ( address.getAddress2() == null ) ? "" : address.getAddress2().trim() ) );
        buf.append ( "]]></address2> \n" );

        buf.append ( "<address3><![CDATA[" );
        buf.append ( ( ( address.getAddress3() == null ) ? "" : address.getAddress3().trim() ) );
        buf.append ( "]]></address3> \n" );

        buf.append ( "<address4><![CDATA[" );
        buf.append ( ( ( address.getAddress4() == null ) ? "" : address.getAddress4().trim() ) );
        buf.append ( "]]></address4> \n" );

        StringBuffer cityStateZip = new StringBuffer ( "" );

        if ( !address.getCity ().equals ( "" ) ) cityStateZip.append ( address.getCity () + ", " );
        if ( !address.getState ().equals ( "" ) ) cityStateZip.append ( address.getState () + " - " );
        if ( !address.getZipCode ().equals ( "" ) ) cityStateZip.append ( address.getZipCode () + ", " );
        cityStateZip.append ( address.getCountry () );

        buf.append ( "<cityStateZip><![CDATA[" + cityStateZip + "]]></cityStateZip>" + "\n" );

        StringBuffer phFax = new StringBuffer ();
        if ( !address.getPhoneNumber ().equals ( "" ) ) phFax.append ( "Ph:" + address.getPhoneNumber () + ", " );
        if ( !address.getFaxNumber ().equals ( "" ) ) phFax.append ( "Fax:" + address.getFaxNumber () );

        buf.append ( "<phoneFax><![CDATA[" + phFax + "]]></phoneFax>" + "\n" );

        buf.append ( "</selfAddress> \n" );

        buf.append ( "<purchaseOrderDetails> \n" );
        buf.append ( "<number><![CDATA[" ) .append( purchaseOrderForm.getPurchaseOrderNumber() ) .append( "]]></number> \n" );
        buf.append ( "<date><![CDATA[" ) .append( ( ( purchaseOrderForm.getPurchaseOrderDate() == null ) ? "" : purchaseOrderForm.getPurchaseOrderDate() ) ) .append( "]]></date> \n" );
        buf.append ( "<poType><![CDATA[" ) .append( purchaseOrderForm.getPoTypeLabel() ) .append( "]]></poType> \n" );
        buf.append ( "<vendorName><![CDATA[" ) .append( ( ( purchaseOrderForm.getVendorName() == null ) ? "" : purchaseOrderForm.getVendorName() ) ) .append( "]]></vendorName> \n" );
        buf.append ( "<validTo><![CDATA[" ) .append( ( ( purchaseOrderForm.getValidToDate() == null ) ? "" : purchaseOrderForm.getValidToDate() ) ) .append( "]]></validTo> \n" );
        buf.append ( "<shipMethod><![CDATA[" ) .append( ( ( purchaseOrderForm.getShipMethod() == null ) ? "" : purchaseOrderForm.getShipMethod() ) ) .append( "]]></shipMethod> \n" );
        buf.append ( "<payTerms><![CDATA[" ) .append( ( ( purchaseOrderForm.getPayTerms() == null ) ? "" : purchaseOrderForm.getPayTerms() ) ) .append( "]]></payTerms> \n" );
        buf.append ( "</purchaseOrderDetails> \n" );

        buf.append ( "<billingAddress> \n" );
        buf.append ( getXMLFormattedAddress( "", address.getContactPerson(), address.getAddress1(), address.getAddress2(), address.getAddress3(), address.getAddress4(), address.getCity(), address.getState(), address.getZipCode(), address.getCountry(), address.getPhoneNumber(), address.getCellNumber(), address.getFaxNumber(), address.getEmail() ) );
        buf.append ( "</billingAddress> \n" );

        buf.append ( "<shipToAddress> \n" );
        Address s_address = new Address();
        try
        {
            s_address  = purchaseOrderForm.getShippingAddress();
        }
        catch( Exception e)
        {
            e.printStackTrace();
        }
        buf.append ( getXMLFormattedAddress( s_address.getContactPerson(), s_address.getContactPerson(), s_address.getAddress1(), s_address.getAddress2(), s_address.getAddress3(), s_address.getAddress4(), s_address.getCity(), s_address.getState(), s_address.getZipCode(), s_address.getCountry(), s_address.getPhoneNumber(), s_address.getCellNumber(), s_address.getFaxNumber(), s_address.getEmail() ) );
        buf.append ( "</shipToAddress> \n" );

        buf.append ( "<Comments><![CDATA[" );
        buf.append ( ( ( purchaseOrderForm.getComments() == null ) ? "" : purchaseOrderForm.getComments().trim() ) );
        buf.append ( "]]></Comments> \n" );

        buf.append ( "<lineItems> \n" );
        int index = 1;
        if ( poLineItems != null )
        {
            for ( int i = 0; i < poLineItems.size(); i++)
            {
                PurchaseOrderLineItem poLineItem = ( PurchaseOrderLineItem ) poLineItems.get( i );
                if( !Constants.PURCHASE_ORDER_STATUS_CANCELLED.equalsIgnoreCase( poLineItem.getStatus() ) )
                {
                    buf.append ( "<lineItem> \n" );
                    buf.append ( "<poLineItem><![CDATA[" ) .append ( index++ ) .append ( "]]></poLineItem> \n" );
                    buf.append ( "<ProcessName><![CDATA[" ) .append ( poLineItem.getProcessName() ) . append( "]]></ProcessName>\n" );
                    buf.append ( "<PartNumber><![CDATA[" ) .append ( poLineItem.getPartNumber() ) . append( "]]></PartNumber>\n" );
                    buf.append ( "<customerPartNumber><![CDATA[" ) .append ( poLineItem.getCustomerPartNumber() ) . append( "]]></customerPartNumber>\n" );
                    buf.append ( "<description><![CDATA[" );
                    buf.append ( ( ( ( poLineItem.getDescription() == null ) || ( poLineItem.getDescription().trim().length() == 0 ) ) ? "" : poLineItem.getDescription().trim() ) );
                    buf.append ( "]]></description>\n" );
                    buf.append ( "<PakType><![CDATA[" ) .append ( poLineItem.getPackageType() != null ? poLineItem.getPackageType() : "" ) . append( "]]></PakType>\n" );
                    buf.append ( "<requestDate><![CDATA[" ) .append ( poLineItem.getRequestedDate() != null ? poLineItem.getRequestedDate() : "" ) .append ( "]]></requestDate>\n" );
                    buf.append ( "<reqQty><![CDATA[" ) .append( poLineItem.getRequestedQuantity()  ).append ( "]]></reqQty>\n" );
                    buf.append ( "<unitPrice><![CDATA[" + poLineItem.getUnitCostAsString() + "]]></unitPrice>" + "\n" );
                    buf.append ( "<extendedPrice><![CDATA[" + poLineItem.getExtendedCostAsString() + "]]></extendedPrice>" + "\n" );
                    buf.append ( "<status><![CDATA[" + poLineItem.getStatus() + "]]></status>" + "\n" );
                    buf.append ( "</lineItem>" + "\n" );
                }
            }
        }
        buf.append ( "</lineItems> \n" );
        if ( poLineItems != null )
        {
            if( ( index == 1 )&&( poLineItems.size() > 0 ) )
            {
                buf.append ( "<errorMessageDescription><![CDATA[ All Line Items are cancelled ]]></errorMessageDescription>" + "\n" );
            }
            if( ( index != 1 )&&( poLineItems.size() > 0 ) )
            {
                buf.append ( "<total><![CDATA[" + purchaseOrderForm.getSubTotalAsString() + "]]></total>" + "\n" );
                buf.append ( "<tradeDiscount><![CDATA[" + purchaseOrderForm.getTradeDiscountAsString() + "]]></tradeDiscount>" + "\n" );
                buf.append ( "<freight><![CDATA[" + purchaseOrderForm.getFreightAsString() + "]]></freight>" + "\n" );
                buf.append ( "<misc><![CDATA[" + purchaseOrderForm.getMiscellaneousAsString() + "]]></misc>" + "\n" );
                buf.append ( "<tax><![CDATA[" + purchaseOrderForm.getTaxAsString() + "]]></tax>" + "\n" );
                buf.append ( "<orderTotal><![CDATA[" + purchaseOrderForm.getTotalAsString() + "]]></orderTotal>" + "\n" );
            }
        }
        buf.append ( "</purchaseOrder> \n" );
        //System.out.println("\n\n PDF--XML \n" + buf.toString() + "\n");
        return buf.toString();
    }

    public static String getFormatedState( String state, String zipCode, String country )
    {
        String addr = "";
        if (   state != null  &&   state.trim().length() != 0 )
            addr =   state;
        if ( zipCode != null &&  zipCode.trim().length() != 0 )
        {
            if ( addr.trim().length() !=0 )
                addr = addr + "&nbsp;-&nbsp;" + zipCode;
            else
                addr = addr + zipCode;
        }
        if (   country != null  &&  country.trim().length() != 0  )
        {
            if ( addr.trim().length() != 0 )
                addr = addr + ",&nbsp;" + country;
            else
                addr = addr + country;
        }
        return addr.replaceAll("&nbsp;"," ");
    }

    public static String getFormattedAddress (String name, String contactName, String address1, String address2, String address3, String address4, String city, String state, String zipCode, String country, String phoneNumber, String cellNumber, String faxNumber, String emailId )
    {
        StringBuffer buffStr = new StringBuffer();
        String formatedAddresses =  null;

        if ( name != null  )
        {
            if ( ( contactName != null ) && ( contactName.trim().length() > 0 ) )
            {
                if ( ! name.equalsIgnoreCase( contactName ) )
                {
                    buffStr.append( ( name.trim().length() > 0 ) ? name + "<BR>" : "" );
                    buffStr.append( ( ( contactName == null ) || ( contactName.trim().length() == 0 ) ) ? "" : contactName );
                }
                else
                {
                    buffStr.append( ( name.trim().length() > 0 ) ? name  : "" );
                }
            }
            else
            {
                buffStr.append( ( name.trim().length() > 0 ) ? name  : "" );
            }
        }
        else
        {
            buffStr.append( ( ( contactName == null ) || ( contactName.trim().length() == 0 ) ) ? "" : contactName );
        }
        buffStr.append ( ( ( address1   == null ) || (  address1.trim().length()    == 0 ) ) ? "" : "<BR>"  +  address1   );
        buffStr.append ( ( ( address2   == null ) || (  address2.trim().length()    == 0 ) ) ? "" : "<BR>"  +  address2   );
        buffStr.append ( ( ( address3   == null ) || (  address3.trim().length()    == 0 ) ) ? "" : "<BR>"  +  address3   );
        buffStr.append ( ( ( address4   == null ) || (  address4.trim().length()    == 0 ) ) ? "" : "<BR>"  +  address4   );
        buffStr.append ( ( ( city       == null ) || (  city.trim().length()        == 0 ) ) ? "" : "<BR>"  +  city       );

        String formatedState = getFormatedState( state, zipCode, country );
        if ( formatedState.trim().length() > 0 )
        {
             buffStr.append ( "<BR>" + formatedState );
        }

        buffStr.append ( ( ( phoneNumber    != null ) && ( phoneNumber.trim().length()  > 0 ) ) ?  "<BR>Tel: "      + phoneNumber   : "" );
        buffStr.append ( ( ( cellNumber     != null ) && ( cellNumber.trim().length()   > 0 ) ) ?  "<BR>Cell: "  + cellNumber    : "");
        buffStr.append ( ( ( faxNumber      != null ) && ( faxNumber.trim().length()    > 0 ) ) ?  "<BR>Fax: "      + faxNumber     : "" );
        buffStr.append ( ( ( emailId        != null ) && ( emailId.trim().length()      > 0 ) ) ?  "<BR>Email: "    + emailId       : "" );

        formatedAddresses = buffStr.toString();
        formatedAddresses = formatedAddresses.replaceAll("<br><br>","<br>");
        formatedAddresses = formatedAddresses.replaceAll("<br><br><br>","<br>");
        if( formatedAddresses.length() > 4 && formatedAddresses.substring(0,4).equalsIgnoreCase("<br>") )
        {
            try{
                formatedAddresses = formatedAddresses.substring( 4 , formatedAddresses.length() );
            }catch(Exception e){
                System.out.println("-----------ERROR = " + e);
            }
        }
        return  formatedAddresses ;
    }

    public static String getXMLFormattedAddress( String name, String contactName, String address1, String address2, String address3, String address4, String city, String state, String zipCode, String country, String phoneNumber, String cellNumber, String faxNumber, String emailId  )
    {

        StringBuffer formatAddress = new StringBuffer();

        formatAddress.append ( "<name><![CDATA[" );
        formatAddress.append ( ( ( name == null ) || ( ( name.trim().length() == 0 ) ) ) ? "" : name );
        formatAddress.append ( "]]></name> \n" );

        if( ( name != null ) && ( name.equalsIgnoreCase( contactName ) ) )
        {
            formatAddress.append ( "<contactname><![CDATA[ ]]></contactname> \n" );
        }
        else
        {
            formatAddress.append ( "<contactname><![CDATA[" );
            formatAddress.append ( ( ( contactName == null ) || ( ( contactName.trim().length() == 0 ) ) ) ? "" : contactName );
            formatAddress.append ( "]]></contactname> \n" );
        }

        formatAddress.append ( "<address1><![CDATA[" );
        formatAddress.append ( ( ( address1 == null ) || ( ( address1.trim().length() == 0 ) ) ) ? "" : address1 );
        formatAddress.append ( "]]></address1> \n" );

        formatAddress.append ( "<address2><![CDATA[" );
        formatAddress.append ( ( ( address2 == null ) || ( ( address2.trim().length() == 0 ) ) ) ? "" : address2 );
        formatAddress.append ( "]]></address2> \n" );

        formatAddress.append ( "<address3><![CDATA[" );
        formatAddress.append ( ( ( address3 == null ) || ( ( address3.trim().length() == 0 ) ) ) ? "" : address3 );
        formatAddress.append ( "]]></address3> \n" );

        formatAddress.append ( "<address4><![CDATA[" );
        formatAddress.append ( ( ( address4 == null ) || ( ( address4.trim().length() == 0 ) ) ) ? "" : address4 );
        formatAddress.append ( "]]></address4> \n" );

        formatAddress.append ( "<city><![CDATA[" );
        formatAddress.append ( ( ( city == null ) || ( city.trim().length()==0 ) ) ? "" : city );
        formatAddress.append ( "]]></city> \n" );

	    String formatedState = "";
	    formatedState = getFormatedState( state, zipCode, country );
		if ( formatedState.trim().length() > 0 )
		   formatAddress.append( "<state><![CDATA["+formatedState+"]]></state> \n" );

        formatAddress.append ( "<phone><![CDATA[" );
        formatAddress.append ( ( ( phoneNumber != null ) && ( phoneNumber.trim().length() > 0 ) ) ?  "Tel: "+ phoneNumber +"" : "" );
        formatAddress.append ( "]]></phone> \n" );

        formatAddress.append ( "<cell><![CDATA[" );
        formatAddress.append ( ( ( cellNumber != null ) && ( cellNumber.trim().length() > 0 ) ) ?  "Cell: "+ cellNumber +"" : "" );
        formatAddress.append ( "]]></cell> \n" );

        formatAddress.append ( "<fax><![CDATA[" );
        formatAddress.append ( ( ( faxNumber != null ) && ( faxNumber.trim().length() > 0 ) ) ? "Fax: "+ faxNumber : "" );
        formatAddress.append ( "]]></fax> \n" );

	    formatAddress.append ( "<email><![CDATA[" );
        formatAddress.append ( ( ( emailId != null ) && ( emailId.trim().length() > 0 ) ) ? "Email: "+ emailId : "" );
        formatAddress.append ( "]]></email> \n" );

        return formatAddress.toString() ;
    }

    public int getShippingMethodId() {
        return shippingMethodId;
    }

    public void setShippingMethodId(int shippingMethodId) {
        this.shippingMethodId = shippingMethodId;
    }

    public String getPayTerms() {
        return payTerms;
    }

    public void setPayTerms(String payTerms) {
        this.payTerms = payTerms;
    }

    public ArrayList getShippingMethodsList() {
        return shippingMethodsList;
    }

    public void setShippingMethodsList(ArrayList shippingMethodsList) {
        this.shippingMethodsList = shippingMethodsList;
    }

    public ArrayList getPayTermsList() {
        return payTermsList;
    }

    public void setPayTermsList(ArrayList payTermsList) {
        this.payTermsList = payTermsList;
    }

    public String getNewShippingMethod() {
        return newShippingMethod;
    }

    public void setNewShippingMethod(String newShippingMethod) {
        this.newShippingMethod = newShippingMethod;
    }

    public String getNewShippingAccount() {
        return newShippingAccount;
    }

    public void setNewShippingAccount(String newShippingAccount) {
        this.newShippingAccount = newShippingAccount;
    }

    public String getNewPayTerms() {
        return newPayTerms;
    }

    public void setNewPayTerms(String newPayTerms) {
        this.newPayTerms = newPayTerms;
    }

    public String getShipMethod() {
        return shipMethod;
    }

    public void setShipMethod(String shipMethod) {
        this.shipMethod = shipMethod;
    }

    public String getValidToDate() {
        return validToDate;
    }

    public void setValidToDate(String validToDate) {
        this.validToDate = validToDate;
    }

    public double getPoMaxAmt() {
        return poMaxAmt;
    }

    public void setPoMaxAmt(double poMaxAmt) {
        this.poMaxAmt = poMaxAmt;
    }

    public double getPrevReceiptsTotal() {
        return prevReceiptsTotal;
    }

    public void setPrevReceiptsTotal(double prevReceiptsTotal) {
        this.prevReceiptsTotal = prevReceiptsTotal;
    }
}
